//
//  LHPhotoAlbumManager.m
//  BaiSi
//
//  Created by mac on 16/11/5.
//  Copyright © 2016年 DeYi. All rights reserved.
//

#import "LHPhotoAlbumManager.h"

@implementation LHPhotoAlbumManager

// 指定一个相册名字.获取相册
+ (PHAssetCollection *)fetchAssetCollection:(NSString *)title
{
    // 遍历相簿里面所有相册
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle isEqualToString:title]) {
            // 获取到已经创建好相册
            return assetCollection;
        }
    }
    return nil;
    
}


// 保存图片
+ (void)savePhoto:(UIImage *)image albumTitle:(NSString *)albumTitle completionHandler:(void (^)(BOOL, NSError *))completionHandler
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        // 做一些相簿操作
        
        // 0.判断下相册是否已经存在
        PHAssetCollection *assetCollection = [LHPhotoAlbumManager fetchAssetCollection:albumTitle];
        
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest = nil;
        
        if (assetCollection) { // 已经存在相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
        } else {
            // 创建相册
            assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumTitle];
        }
        
        // 2.创建图片请求
        PHAssetCreationRequest *assetCreationRequest = [PHAssetCreationRequest creationRequestForAssetFromImage:image];
        
        // 3.往相册中添加图片
        // NSFastEnumeration: 当做一个数组去用
        [assetCollectionChangeRequest addAssets:@[assetCreationRequest.placeholderForCreatedAsset]];
        
    } completionHandler:completionHandler];
}

//根据App是否被允许使用系统相册功能,再根据情是否把图片保存到指定相册中
+ (void)savePhotoWithAuthorizationStatus:(UIImage *)image albumTitle:(NSString *)albumTitle refuseInfoHandle:(void(^)())refuseInfoHandle completionHandler:(void (^)(BOOL, NSError *))completionHandler {
    /*
     判断下用户是否允许app访问相册
     每次都创建相册
     */
    // 获取app访问相册状态
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    
    if (status == PHAuthorizationStatusAuthorized) { // 授权
        // 保存图片到自己的相册
        [self savePhoto:image albumTitle:albumTitle completionHandler:completionHandler];
        
    } else if (status == PHAuthorizationStatusNotDetermined) { // 不确定
        // 弹出访问相册框请求,让用户决定
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 允许使用
               // 保存图片
               [self savePhoto:image albumTitle:albumTitle completionHandler:completionHandler];
            }
        }];
    } else { // 拒绝
        // 提示用户 允许访问系统相册
        if (refuseInfoHandle) {//用户拒绝后,回调方法
            refuseInfoHandle();
        }
        
    }
    
    
}

@end
